package com.zheng.oss.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.zheng.oss.common.constant.OssResult;
import com.zheng.oss.common.constant.OssResultConstant;
import com.zheng.oss.web.entity.UEditorPut;
import com.zheng.oss.web.service.QiniuOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/17
 * Time: 17:22
 */
@Controller
@RequestMapping("/qiniu/oss")
public class QiniuController {
    @Autowired
    private QiniuOssService service;

    @ResponseBody
    @RequestMapping("/upload")
    public Object upload(@RequestParam("file") CommonsMultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new OssResult(OssResultConstant.SUCCESS, service.upload(inputStream, null));
    }

    @ResponseBody
    @RequestMapping(value = "/uploadUeditor", method = RequestMethod.POST)
    public String uploadUeditor(@RequestParam("file") CommonsMultipartFile file,HttpServletResponse response,HttpServletRequest request) {
        response.setContentType("application/json;charset=UTF-8");
        InputStream inputStream = null;
        UEditorPut uEditorPut= null;
            try {
            inputStream = file.getInputStream();
            uEditorPut = service.uploadUeditor(inputStream, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state","SUCCESS");
        jsonObject.put("original",file.getFileItem().getFieldName());
        jsonObject.put("url",uEditorPut.getUrl());
        jsonObject.put("title",uEditorPut.getKey());
//        jsonObject.put("size",uEditorPut.getFsize());
//        jsonObject.put("type",".jpg");
        return jsonObject.toJSONString();
    }
}